import React, { useState } from 'react';
import s from './style.module.css';
import {
  Table,
  Message,
  Button,
  Pagination,
  Confirm,
  Form,
  Input,
  Dialog
} from '@knownsec/react-component';
import cn from 'classnames';
import recursionForm from '@/common/recursionForm';
import { warnAddUser, putWarnUser, delWarnUser, getWarnUserList } from '~/API';
export default function email() {
  const [refe, setRefe] = useState(false);
  const [selTable, setSelTable] = useState([]);
  const [tableData, setTableData] = useState({ data: [], total: 0 });
  const [searchInfo, setSearchInfo] = useState({ page: 1, limit: 10 });
  const createForm = React.useRef();
  const validatormap = (rule, value, callback) => {
    const reg = new RegExp(
      '^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$'
    );
    if (rule.field == 'fname' && !value) {
      callback('请填写联系人');
    } else if (rule.field == 'email' && !reg.test(value)) {
      callback('请填写邮件地址');
    } else {
      return Promise.resolve();
    }
  };
  const columns = [
    {
      title: '告警联系人',
      dataIndex: 'contact_name',
    },
    {
      title: '发件邮箱',
      dataIndex: 'sender',
    },
    {
      title: '收件邮箱',
      dataIndex: 'receiver_email',
    },
    {
      title: '操作',
      dataIndex: 'option',
      render: (e, row) => {
        return (
          <>
            <span
              className={s.operation}
              onClick={() => {
                showDialog(row);
              }}
            >
              修改
            </span>
            <span
              className={s.operation}
              onClick={() => {
                delDia([row.id]);
              }}
            >
              删除
            </span>
          </>
        );
      },
    },
  ];
  const getList = async (e) => {
    setSelTable([])
    setRefe(!refe)
    const res = await getWarnUserList(e);
    let data = [];
    if (res.data.data) {
      data = res.data.data.map((e) => {
        e.id = e.receiver_id;
        return e;
      });
    }

    setTableData({ data, total: res.data.total });
  };
  const delDia = (e) => {
    Confirm({
      pro: true,
      className: s.dialogName,
      title: '删除告警联系人',
      message: <div className={s.delBox}>确认删除选中的告警联系人？</div>,
      onconfirm: async () => {
        const params = {
          receiver_ids: e || selTable,
        };
        const res = await delWarnUser(params);
        if (res.status === 'success') {
          setSelTable([]);
          setRefe(!refe)
          Message.show({
            pro: true,
            type: 'success',
            message: '删除成功',
            showClose: false,
          });
          onSearch({ page: 1, limit: 10 });
        }
      },
    });
  };
  const [dialogTitle, setDialogTitle] = useState('添加告警联系人')
  const [visible, setVisible] = useState(false)
  const showDialog = (row = {}) => {
    setVisible(true)
    if (row) {
      setDialogTitle('修改告警联系人');
    }
  };
  const onValues = (data) => {
    let values = recursionForm(data);
    createForm.current.setFieldsValue(values);
  };
  const dialogSubmit = async () => {
    const data = await createForm.current.validateFields();
    let res = null;
    if (dialogTitle === '添加告警联系人') {
      res = await warnAddUser({ contact_name: Object.keys(data)[0] === 'fname' ? data.fname : '', receiver_email: Object.keys(data)[0] === 'fname' ? '' : data.email }).catch((err) => {
        return err;
      });
    } else {
      res = await putWarnUser({
        receiver_id: row.receiver_id,
        data: { receiver_email: email },
      }).catch((err) => {
        return err;
      });
    }
    if (res.status === 'success') {
      onSearch({ page: 1, limit: 10 });
      Message.show({
        pro: true,
        type: 'success',
        message: '操作成功',
        showClose: false,
      });
    } else {
      const typeObj = { contact_name: '联系人名称', receiver_email: '邮箱' };
      const msg = Object.values(res.data)[0];
      const name = typeObj[Object.keys(res.data)[0]];
      const errmsg_=`${name}:${msg}`.replace('undefined:','')
      Message.show({
        pro: true,
        type: 'error',
        message: errmsg_,
        showClose: false,
      });
    }
  }
  const onSearch = (e) => {
    setSearchInfo({ page: e.page, limit: e.limit });
    let params = { page: e.page, limit: e.limit };
    getList(params);
  };
  React.useMemo(() => {
    getList({ page: 1, limit: 10 });
  }, []);
  return (
    <div className={s.tableBox}>
      <div className={s.tool}>
        <Button
          pro
          type="primary"
          onClick={() => {
            showDialog(false);
          }}
        >
          添加联系人
        </Button>
      </div>
      <div>
        <Button
          pro
          type="text"
          className="delete-btn p0"
          disabled={!selTable.length}
          onClick={() => {
            delDia();
          }}
        >
          批量删除
        </Button>
      </div>
      <Table
        selectable
        refre={refe}
        columns={columns}
        className={selTable.length ? 'half-select' : ''}
        data={tableData.data}
        getCheckedList={(e) => {
          setSelTable(e);
        }}
      ></Table>
      {tableData.total > 10 && <Pagination
        key={Number(123)}
        className={s.pagination}
        current={searchInfo.page}
        showQuickJumper={{ goButton: true }}
        showTotal={(total) => `共${total}条`}
        showSizeChanger={true}
        pageSize={searchInfo.limit}
        pageSizeOptions={['10', '20', '50']}
        total={tableData.total}
        onChange={(page, limit) => {
          onSearch({ page, limit });
        }}
      />}
      <Dialog 
        title={dialogTitle} 
        visible={visible} 
        onhide={() => setVisible(false)} 
        onsubmit={dialogSubmit} >
        <Form
          ref={createForm}
          onValuesChange={(newItem, allValues) => {
            onValues(newItem, allValues);
          }}
        >
          <Form.Item
            rules={[{ required: true, validator: validatormap }]}
            name="fname"
            label="告警联系人名称"
            initialValue={row.contact_name}
          >
            <Input
              pro
              autoComplete={'off'}
              disabled={row}
              className={s.inpName}
              maxlength={50}
              placeholder="请输入联系人名称"
            ></Input>
          </Form.Item>
          <Form.Item
            rules={[{ required: true, validator: validatormap }]}
            name="email"
            label="邮箱"
            initialValue={row.receiver_email}
          >
            <Input
              pro
              autoComplete={'off'}
              className={s.inpName}
              maxlength={50}
              placeholder="请输入邮箱地址"
            ></Input>
          </Form.Item>
        </Form>
      </Dialog>
    </div>
  );
}
